﻿using System;
using System.ComponentModel;
using System.Xml;

namespace PatientRegisterService.Utils
{
    public class XMLHelper
    {
        //根据实体生成数据
        public static XmlElement XmlData(object t, string outStr, XmlDocument xmldoc, XmlElement xmlList)
        {
            XmlElement outElement = xmldoc.CreateElement(outStr);

            foreach (System.Reflection.PropertyInfo property in t.GetType().GetProperties())
            {
                Object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objs.Length == 0)
                {
                    XmlElement xmlElement = xmldoc.CreateElement(property.Name);
                    try
                    {
                        XmlText xmlText = xmldoc.CreateTextNode(property.GetValue(t).ToString());
                        xmlElement.AppendChild(xmlText);
                    }
                    catch (NullReferenceException)
                    {
                        XmlText xmlText = xmldoc.CreateTextNode("");
                        xmlElement.AppendChild(xmlText);
                    }
                    outElement.AppendChild(xmlElement);
                }
            }
            xmlList.AppendChild(outElement);
            return xmlList;
        }

        //头信息
        public static XmlElement XmlHeader(XmlDocument xmldoc, string code, string desc)
        {
            xmldoc.RemoveAll();
            XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmldoc.AppendChild(xmldecl);
            //加入一个根元素
            XmlElement xmlRoot = xmldoc.CreateElement("Response");
            xmldoc.AppendChild(xmlRoot);
            //信息头
            XmlElement messageHeader = xmldoc.CreateElement("MessageHeader");
            //账号信息
            XmlElement accessAccount = xmldoc.CreateElement("code");
            XmlText accessAccountText = xmldoc.CreateTextNode(code);
            accessAccount.AppendChild(accessAccountText);
            //签名
            XmlElement sign = xmldoc.CreateElement("desc");
            XmlText signText = xmldoc.CreateTextNode(desc);
            sign.AppendChild(signText);
            //完成头部信息
            messageHeader.AppendChild(accessAccount);
            messageHeader.AppendChild(sign);
            xmlRoot.AppendChild(messageHeader);
            return xmlRoot;
        }
    }
}
